/*
 * Copyright (c) 2017-2021 duobaoyu, Inc. All rights reserved.<br/>
 * Unless required by applicable law or agreed to in writing, <br/>
 * Unauthorized use and distribution by any person or organization is prohibited.<br/>
 */
package com.shangsi.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author dzd
 * @date 2021-12-25
 */
@Component
@Order(1)
public class AuthorizeFilter implements GlobalFilter // 或者实现也可以设置order, PriorityOrdered
{
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 请求参数获取
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        //2.获取参数中的authorization
        String authorization = queryParams.getFirst("authorization");

        //3.判断参数值是否等于admin
        if ("admin".equals(authorization)){
            //4.是 放行
            return chain.filter(exchange);
        }
        System.out.println("--------------401--------------------------");
        //5.否
        //5.1 设置状态码
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        //5.2 拦截请求
        return exchange.getResponse().setComplete();

    }

  /*  @Override
    public int getOrder() {
        return 0;
    }*/
}
